/**
 * TODOList的视图
 */

import xs, { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import { TodoListState } from '../../types';

 /**
  * 返回组件视图
  */
 export default function view(state$ : Stream<TodoListState>, listVDom$ : Stream<VNode>) : Stream<VNode> {
    return xs.combine(state$, listVDom$)
            .map(([{ inputValue, list }, listVDom]) => {
                // 是否全部已完成
                const allCompleted = list.reduce((x, y) => x && y.completed, true);
                // 根据列表长度切换class
                const sectionStyle = {'display': list.length ? '' : 'none'};
                const amountCompleted = list
                    .filter(item => item.completed)
                    .length;
                const amountActive = list.length - amountCompleted;
                const footerStyle = {'display': list.length ? '' : 'none'};
                return <div>
                    <header className='header'>
                        <h1>todos</h1>
                        <input 
                            className='new-todo' 
                            type='text' 
                            placeholder='What needs to be done?' 
                            autofocus 
                            name='newTodo'
                            value={inputValue}/>
                    </header>
                    <section 
                        className='main'
                        style={sectionStyle}>
                        <input
                            id='toggle-all' 
                            className='toggle-all' 
                            type='checkbox'
                            checked={allCompleted}/>
                        <label htmlFor='toggle-all'>Mark all as complete</label>
                        {listVDom}
                    </section>
                    <footer 
                        className='footer'
                        style={footerStyle}> 
                        <span className='todo-count'><strong>{amountActive}</strong>
                            {' item' + (amountActive !== 1 ? 's' : '') + ' left'}
                        </span>
                        <ul className='filters'>
                            <li><a href="/">All</a></li>
                            <li><a href="/active" className="active">Active</a></li>
                            <li><a href="/completed" className="completed">Completed</a></li>
                            {amountCompleted > 0 ? <button className='clear-completed'>Clear completed ({amountCompleted})</button> : null}
                        </ul>
                    </footer>
                </div>
            });
 }